package com.bdth.bdthiss.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.bdth.bdthiss.entity.*;
import com.bdth.bdthiss.jsoup.GoodsNoTools;
import com.bdth.bdthiss.jsoup.OfficemateTools;
import com.bdth.bdthiss.service.BrandService;
import com.bdth.bdthiss.service.BrandsService;
import com.bdth.bdthiss.service.CategoryService;
import com.bdth.bdthiss.service.ExcelgoodsService;
import com.bdth.bdthiss.vo.CommonResult;
import com.bdth.bdthiss.vo.MessageResult;
import com.bdth.bdthiss.vo.PageVo;
import com.bdth.bdthiss.vo.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LGP
 * @since 2020-04-06
 */
@Controller
@RequestMapping("/excelgoods")
public class ExcelgoodsController {

    @Autowired
    private ExcelgoodsService excelgoodsService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private BrandsService brandsService;

    @Autowired
    private Environment env;


    @RequestMapping(value = "index")
    public String index() {
        return "excelgoods/index";
    }

    @RequestMapping(value = "search")
    public String search() {
        return "excelgoods/search";
    }

    @RequestMapping(value = "update")
    public String update() {
        return "excelgoods/update";
    }

    @RequestMapping(value = "list")
    @ResponseBody
    public PageVo<Excelgoods> getPageList(HttpServletRequest request, Pagination<Excelgoods> pagination,
                                          @RequestParam Integer status,
                                          @RequestParam(required = false) String skuid,
                                          @RequestParam(required = false) String goodsname,
                                          @RequestParam(required = false) String brand
    ){
        Map<String, Object> query = new HashMap<>();
        query.put("status",status);
        if(goodsname!=null && !goodsname.equals(""))
            query.put("goodsname",goodsname);
        if(skuid!=null && !skuid.equals(""))
            query.put("skuid",skuid);
        if(brand!=null && !brand.equals(""))
            query.put("brand",brand);
        Page<Excelgoods> items =  excelgoodsService.listPages(pagination,query);
        PageVo<Excelgoods> pageVo = new PageVo<>(items.getRecords(),items.getTotal());
        return pageVo;
    }

    @RequestMapping(value = "download")
    @ResponseBody
    public MessageResult update(@RequestParam String id){
        Excelgoods bean = excelgoodsService.selectById(id);
        String saveWhere = env.getProperty("data.save.where");
//        String saveWhere = imgAddress;
        Map<String, String> result = null;
        try {
            result = OfficemateTools.getHtmlAndDownPic(bean.getSkuid(), bean.getGoodsurl(), saveWhere);
        }catch (Exception e){
            return MessageResult.getError("500",e.getMessage());
        }
        bean.setBrand(result.get("brand"));
        bean.setContext(result.get("html"));
        bean.setDown(1);
        excelgoodsService.updateById(bean);
        return MessageResult.getSuccess("商品数据下载成功");
    }

    @RequestMapping(value = "form")
    public String form() {
        return "excelgoods/form";
    }

    @RequestMapping(value = "newno")
    @ResponseBody
    public CommonResult newno(){
        String goodsno = GoodsNoTools.createGoodsNo();
        return CommonResult.success(goodsno);
    }

    @RequestMapping(value = "findtype")
    @ResponseBody
    public CommonResult findtype(@RequestParam String typename){
        EntityWrapper<Category> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("name",typename.trim());
        List<Category> list = categoryService.selectList(entityWrapper);
        if(list!=null && list.size()>0){
            Category bean = list.get(0);
            return CommonResult.success(bean.getId());
        }
        return CommonResult.fail("平台没有相关商品类型,重新添加或修改");
    }

    @RequestMapping(value = "findbrand")
    @ResponseBody
    public CommonResult findbrand(@RequestParam String brand){
        EntityWrapper<Brands> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("cnname",brand.trim()).or().eq("enname",brand.trim()).or().eq("alisname",brand.trim());
        List<Brands> list = brandsService.selectList(entityWrapper);
        if(list!=null && list.size()>0){
            Brands bean = list.get(0);
            return CommonResult.success(bean.getBrandid());
        }
        return CommonResult.fail("平台没有相关商品类型,重新添加或修改");
    }

    @RequestMapping(value = "findpic")
    @ResponseBody
    public CommonResult findpic(@RequestParam String uid){
        String saveWhere = env.getProperty("data.save.where");
//        String saveWhere = imgAddress;
        File pic = new File(saveWhere+"officemate\\"+uid+"\\thumbnail\\picsn.txt");
        BufferedReader bufferedReader = null;
        String result = "";
        try {
            bufferedReader = new BufferedReader(new FileReader(pic));
            String line = bufferedReader.readLine();
            while (line!=null){
                result += line+"\r\n";
                line = bufferedReader.readLine();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(bufferedReader!=null)
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
        }

        return CommonResult.success(result);
    }

    @RequestMapping(value = "picyl")
    public ModelAndView picyl(HttpServletResponse response,@RequestParam String picsrc){
        response.addHeader("Access-Control-Allow-Origin", "*");
        ModelAndView mv = new ModelAndView();
        mv.addObject("picsrc",picsrc);
        mv.setViewName("excelgoods/picyl");
        return mv;
    }

    @RequestMapping(value = "allupdate")
    @ResponseBody
    public MessageResult deletes(@RequestParam String ids,
                                 @RequestParam(required = false) Integer typeid,
                                 @RequestParam(required = false) Integer brandid,
                                 @RequestParam(required = false) Integer subtypeid){
        String[] id = ids.split(",");
        EntityWrapper<Excelgoods> entityWrapper = new EntityWrapper<>();
        entityWrapper.in("id",id);
        Excelgoods bean = new Excelgoods();
        if(typeid!=null&&typeid!=0)
            bean.setTypeid(typeid);
        if(brandid!=null&&brandid!=0)
            bean.setBrandid(brandid);
        if(subtypeid!=null&&subtypeid!=0)
            bean.setSubtypeid(subtypeid);
        excelgoodsService.update(bean,entityWrapper);
        return MessageResult.getSuccess("数据更新");
    }

    @RequestMapping(value = "ignoreupdate")
    @ResponseBody
    public MessageResult ignoreupdate(@RequestParam String ids){
        String[] id = ids.split(",");
        EntityWrapper<Excelgoods> entityWrapper = new EntityWrapper<>();
        entityWrapper.in("id",id);
        Excelgoods bean = new Excelgoods();
        bean.setStatus(2);
        excelgoodsService.update(bean,entityWrapper);
        return MessageResult.getSuccess("数据更新");
    }
}

